let start = 0;
let startY = 0;
let currentCaptchaId = null;
let movePercent = 0;
const bgImgWidth = $(".bg-img-div").width();
let end = 206;
let startSlidingTime;
let entSlidingTime;
const trackArr = [];


$(function () {
  refreshCaptcha();
})

// 鼠标按下事件
$(".slider-move-btn").mousedown((event) => {
  $(".validateCodeError").css("display", "none");
  startSlidingTime = new Date();
  start = event.pageX;
  startY = event.pageY;
  $(".slider-move-btn").css("background-position", "-5px 31.0092%")
  window.addEventListener("mousemove", move);
  window.addEventListener("mouseup", up);
});

//开始触摸
$(".slider-move-btn").on("touchstart", (event) => {
  console.log("aa")
  startSlidingTime = new Date();
  start = event.pageX;
  startY = event.pageY;
  if (start === undefined) {
    start = event.originalEvent.targetTouches[0].pageX
    startY = event.originalEvent.targetTouches[0].pageY;
  }
  $(".slider-move-btn").css("background-position", "-5px 31.0092%")
  window.addEventListener("touchmove", move);
  window.addEventListener("touchend", up);
});

//移动
function move(event) {
  if (event instanceof TouchEvent) {
    event = event.touches[0];
  }
  let moveX = event.pageX - start;
  let pageX = event.pageX;
  let pageY = event.pageY;
  console.log("x:", pageX, "y:", pageY, "time:", new Date().getTime() - startSlidingTime.getTime());
  trackArr.push({
    x: pageX - start,
    y: pageY - startY,
    t: (new Date().getTime() - startSlidingTime.getTime())
  });
  if (moveX < 0) {
    moveX = 0;
  } else if (moveX > end) {
    moveX = end;
  }
  // if (moveX > 0 && moveX <= end) {
  $(".slider-move-btn").css("transform", "translate(" + moveX + "px, 0px)")
  $(".slider-img-div").css("transform", "translate(" + moveX + "px, 0px)")
  // }
  movePercent = moveX / bgImgWidth;
}

//结束移动
function up(event) {
  entSlidingTime = new Date();
  console.log(currentCaptchaId, movePercent, bgImgWidth);
  window.removeEventListener("mousemove", move);
  window.removeEventListener("mouseup", up);
  valid();
}

//关闭
$(".close-btn").click(() => {
  $(".slider").css("z-index", -2);
});

//刷新
$(".refresh-btn").click(() => {
  refreshCaptcha();
});

//验证
function valid() {
  $(".slider").css("z-index", -2);
  openOrCloseLoading(true);
  console.log("=======================")
  console.log("startTime", startSlidingTime);
  console.log("endTime", entSlidingTime);
  console.log("track", JSON.stringify(trackArr));


  let data = {
    bgImageWidth: bgImgWidth,
    bgImageHeight: $(".slider-img-div").height(),
    sliderImageWidth: $(".slider-img-div").width(),
    sliderImageHeight: $(".slider-img-div").height(),
    startSlidingTime: startSlidingTime,
    entSlidingTime: entSlidingTime,
    trackList: trackArr
  };

  //获取表单中数据
  var arr = [];
  $(".el-input__inner").each(function () {
    var res = $(this).val();
    arr.push(res);
  })

  var form = {
    doctorName: arr[0],
    password: arr[1]
  }

  /**
   * 请求后台登录接口
   */
  $.ajax({
    type: "POST",
    url: "/api/auth/sys/login",
    contentType: "application/json", //必须这样写
    dataType: "json",
    data: JSON.stringify({
      "id": currentCaptchaId,
      "sliderCaptchaTrack": data,
      "form": form
    }), 
    success: function (res) {
      //由于这里是外部js，所以暂时保存在 sessionStorage 中
      sessionStorage.obj = JSON.stringify(res);
      //验证码输入错误
      if (res.code == 2) {
        $(".validateCodeError").css("display", "block");
        refreshCaptcha();
        setTimeout(() => {
          $(".slider").css("z-index",999);
        }, 200);
      }
      //用户名和密码输入错误
      else if (res.code == 401) {
        $(".err").css("display", "block");
        $(".slider").css("z-index", -2);
        refreshCaptcha();
      } else if (res.code == 0) {
        //调用vue中的方法，将数据存储到 Vuex 中，并将 sessionStorage 中的数据删除
        addData();
      }
      openOrCloseLoading(false);


    }
    
  })

}

/**
 * 滑块验证码重置
 */
function refreshCaptcha() {
  $.get("/api/auth/gen", function (data) {
    reset();
    currentCaptchaId = data.id;
    $("#bg-img").attr("src", data.captcha.backgroundImage);
    $("#slider-img").attr("src", data.captcha.sliderImage);
  })
}

//数据归零
function reset() {
  $(".slider-move-btn").css("background-position", "-5px 11.79625%")
  $(".slider-move-btn").css("transform", "translate(0px, 0px)")
  $(".slider-img-div").css("transform", "translate(0px, 0px)")
  start = 0;
  startSlidingTime = null;
  entSlidingTime = null;
  trackArr.length = 0;
  movePercent = 0;
  currentCaptchaId = null;
  startY = 0;
}

//抛出
module.exports = {
  valid
}
